import { Render, ResourceTypes, SchemaTypes } from '../lib/index';
import { BasicImage, ScrollImage } from './image-filter-shaders';
import imageSrc from '../res/images/DSCF2535.jpg';
import { createRect } from './graphics-utils';

const { VertexBuffers, IndexBuffer, Uniforms, Textures } = ResourceTypes;

let element = document.createElement('canvas');
element.id = 'webgl';
element.width = 1280;
element.height = 1280;
element.style.border = '5px solid #000000';
document.body.appendChild(element);

let canvas = document.getElementById('webgl');
const render = new Render(canvas);

const shader = render.shader(ScrollImage);

const quad = createRect();
const quadBuffers = [render.resource(VertexBuffers, quad.vertex), render.resource(IndexBuffer, quad.index)];
const options = render.resource(Uniforms);
const textures = render.resource(Textures);

function renderFunc() {
    const aspectRatio = image.naturalWidth / image.naturalHeight;
    const imageState = { image, flip: true };
    canvas.height = 720;
    canvas.width = 720 * aspectRatio;
    textures.set('img', imageState);
    render.clear([0.5, 0.5, 0.5, 1.0]).draw(shader, ...quadBuffers, options, textures);
}

let image = new Image();
image.src = imageSrc;
image.onload = function () {
    runMainLoop();
};

let offset = 1.0;
function loop() {
    offset -= 0.01;
    if (offset <= 0) {
        offset = 1.0;
    }
    options.set('offset', offset);
    renderFunc();
}

let intervalId;
let time = 0;
function runMainLoop() {
    let callback = (now) => {
        intervalId = window.requestAnimationFrame(callback);
        time = now;
        loop();
    };
    intervalId = window.requestAnimationFrame(callback);
}
